import React, { createContext, useContext, useState, useEffect, useCallback } from 'react';
import { Friend, FriendService } from './services/FriendService';
import { useAuth } from '../auth/AuthContext';

interface FriendsContextType {
  friends: Friend[];
  loading: boolean;
  error: string | null;
  addFriend: (friendId: number) => Promise<void>;
  removeFriend: (friendId: number) => Promise<void>;
  checkFriendship: (friendId: number) => Promise<boolean>;
  refreshFriends: () => Promise<void>;
}

const FriendsContext = createContext<FriendsContextType | undefined>(undefined);

export const useFriends = () => {
  const context = useContext(FriendsContext);
  if (!context) {
    throw new Error('useFriends must be used within a FriendsProvider');
  }
  return context;
};

interface FriendsProviderProps {
  children: React.ReactNode;
}

export const FriendsProvider: React.FC<FriendsProviderProps> = ({ children }) => {
  const [friends, setFriends] = useState<Friend[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const { user } = useAuth();

  const refreshFriends = useCallback(async () => {
    try {
      // 如果用户未登录，则不获取好友列表
      if (!user) {
        setFriends([]);
        return;
      }
      
      setLoading(true);
      setError(null);
      const friendsList = await FriendService.getFriendList();
      setFriends(friendsList);
    } catch (err) {
      setError('获取好友列表失败');
      console.error('Failed to fetch friends:', err);
    } finally {
      setLoading(false);
    }
  }, [user]);

  const addFriend = async (friendId: number) => {
    try {
      setLoading(true);
      setError(null);
      await FriendService.addFriend(friendId);
      await refreshFriends();
    } catch (err) {
      setError('添加好友失败');
      console.error('Failed to add friend:', err);
      throw err;
    } finally {
      setLoading(false);
    }
  };

  const removeFriend = async (friendId: number) => {
    try {
      setLoading(true);
      setError(null);
      await FriendService.removeFriend(friendId);
      await refreshFriends();
    } catch (err) {
      setError('删除好友失败');
      console.error('Failed to remove friend:', err);
      throw err;
    } finally {
      setLoading(false);
    }
  };

  const checkFriendship = async (friendId: number) => {
    try {
      return await FriendService.checkFriendship(friendId);
    } catch (err) {
      console.error('Failed to check friendship:', err);
      return false;
    }
  };

  // 在用户状态变化时刷新好友列表
  useEffect(() => {
    refreshFriends();
  }, [refreshFriends, user]);

  const value = {
    friends,
    loading,
    error,
    addFriend,
    removeFriend,
    checkFriendship,
    refreshFriends,
  };

  return (
    <FriendsContext.Provider value={value}>
      {children}
    </FriendsContext.Provider>
  );
};